package com.andatsoft.laisim.activity.setting;

import java.io.File;
import java.io.FileFilter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.andatsoft.laisim.R;
import com.andatsoft.laisim.activity.BaseActivity;
import com.andatsoft.laisim.db.DataBaseAccess;
import com.andatsoft.laisim.dialog.ThemeChooserDialog;
import com.andatsoft.laisim.entity.ThemeItem;
import com.andatsoft.laisim.theme.ThemeManager;
import com.andatsoft.laisim.utils.ToastMessage;
import com.andatsoft.laisim.view.WPProgressBar;

public class ThemeSettingActivity extends BaseActivity {

	private LinearLayout mLayoutThemeScan;
	private LinearLayout mLayoutThemeSelect;
	private LinearLayout mLayoutThemeSelectOnline;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setting_theme);
		initViews();
		setupListeners();
	}

	private void initViews() {
		((TextView) findViewById(R.id.tv_setting_theme_name))
				.setText(getString(R.string.setting_theme_current_theme_skin_sub_1)
						+ ": " + ThemeManager.getSelectedTheme().getThemeName());
		((TextView) findViewById(R.id.tv_setting_theme_author))
				.setText(getString(R.string.setting_theme_current_theme_skin_sub_2)
						+ ": "
						+ ThemeManager.getSelectedTheme().getAuthorName());
		((TextView) findViewById(R.id.tv_setting_theme_info))
				.setText(getString(R.string.setting_theme_current_theme_skin_sub_3)
						+ ": "
						+ ThemeManager.getSelectedTheme().getAuthorInfo());
		mLayoutThemeScan = (LinearLayout) findViewById(R.id.layout_setting_theme_scan);
		mLayoutThemeSelect = (LinearLayout) findViewById(R.id.layout_setting_theme_select_theme);
		mLayoutThemeSelectOnline = (LinearLayout) findViewById(R.id.layout_setting_theme_select_theme_online);

	}

	private void setupListeners() {
		mLayoutThemeScan.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					v.setBackgroundColor(0x50ffffff);
					return true;
				case MotionEvent.ACTION_UP:
					v.setBackgroundColor(0xff000000);
					new ThemeScanner().execute();
					return true;
				case MotionEvent.ACTION_CANCEL:
					v.setBackgroundColor(0xff000000);
					return true;
				}
				return false;
			}
		});

		mLayoutThemeSelect.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					v.setBackgroundColor(0x50ffffff);
					return true;
				case MotionEvent.ACTION_UP:
					v.setBackgroundColor(0xff000000);
					startActivity(new Intent(ThemeSettingActivity.this,
							ThemeChooserDialog.class));
					return true;
				case MotionEvent.ACTION_CANCEL:
					v.setBackgroundColor(0xff000000);
					return true;
				}
				return false;
			}
		});

		mLayoutThemeSelectOnline.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					v.setBackgroundColor(0x50ffffff);
					return true;
				case MotionEvent.ACTION_UP:
					v.setBackgroundColor(0xff000000);
					new ToastMessage(getApplicationContext())
							.showLongMessage("This feature is still in progress. :");
					return true;
				case MotionEvent.ACTION_CANCEL:
					v.setBackgroundColor(0xff000000);
					return true;
				}
				return false;
			}
		});

	}

	class ThemeScanner extends AsyncTask<Void, Void, Integer> {

		@Override
		protected void onPreExecute() {
			mLayoutThemeScan.setEnabled(false);
			((WPProgressBar) findViewById(R.id.wp_progress_theme_scan))
					.setVisibility(View.VISIBLE);
		}

		@Override
		protected Integer doInBackground(Void... params) {
			int themeFound = 0;
			String path = Environment.getExternalStorageDirectory()
					+ "/Laisim/Theme/";
			File f = new File(path);
			if (!f.exists())
				f.mkdirs();
			File[] fList = f.listFiles(new FileFilter() {

				@Override
				public boolean accept(File pathname) {
					String name = pathname.getAbsolutePath();
					if (name.substring(name.lastIndexOf(".") - 1).contains(
							"lst"))
						return true;
					return false;
				}
			});
			if (fList != null && fList.length > 0) {
				DataBaseAccess db = DataBaseAccess.getInstance(getApplicationContext());;
				for (int i = 0; i < fList.length; i++) {
					ThemeItem item = extractThemename(fList[i]
							.getAbsolutePath());

					// add theme to db
					item.id = (int) db.addThemeInfo(item.name, item.author,
							item.address, false);
					if (item.id != -1)
						themeFound++;
				}
			}
			return themeFound;
		}

		private ThemeItem extractThemename(String input) {
			DocumentBuilderFactory docFactory = DocumentBuilderFactory
					.newInstance();
			Document doc;
			ThemeItem item = new ThemeItem();
			item.address = input;
			item.isSelected = 0;
			try {

				DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
				File xmlFile = new File(input);
				doc = docBuilder.parse(xmlFile);

				doc.getDocumentElement().normalize();

				// get all node with the tag name is LaisimTheme
				NodeList nodeStuList = doc.getElementsByTagName("LaisimTheme");

				// we only have 1 node, so the first node is wanted node
				Node node = nodeStuList.item(0);

				if (node.getNodeType() == Node.ELEMENT_NODE) {
					Element e = (Element) node;

					String text = e.getElementsByTagName("AuthorName").item(0)
							.getTextContent();
					item.author = text;

					text = e.getElementsByTagName("ThemeName").item(0)
							.getTextContent();
					item.name = text;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return item;
		}

		@Override
		protected void onPostExecute(Integer result) {
			mLayoutThemeScan.setEnabled(true);
			((WPProgressBar) findViewById(R.id.wp_progress_theme_scan))
					.setVisibility(View.GONE);
			if (result == null)
				result = 0;
			if (result < 2) {
				new ToastMessage(getApplicationContext())
						.showShortMessage(result + " "
								+ getString(R.string.toast_number_theme_found));
			} else {
				new ToastMessage(getApplicationContext())
						.showShortMessage(result
								+ " "
								+ getString(R.string.toast_number_theme_found_plural));
			}
		}
	}
}
